<template>
  <div class="phenology-management">
    <!-- <div class="page-header">
      <h1 class="page-title">物候期展示</h1>
      <p class="page-subtitle">查看作物的生长周期和指导信息</p>
    </div> -->

    <!-- 步骤指示器 -->
    <!-- <div class="steps-indicator">
      <div 
        v-for="(step, index) in steps" 
        :key="step.id"
        :class="['step-item', { active: currentStep === index }]"
        @click="setCurrentStep(index)"
      >
        <div class="step-number">{{ index + 1 }}</div>
        <div class="step-info">
          <div class="step-title">{{ step.title }}</div>
          <div class="step-desc">{{ step.description }}</div>
        </div>
      </div>
    </div> -->

    <!-- 抽屉式卡片容器 -->
    <div class="drawer-cards-container">
      <!-- 作物管理卡片 -->
      <transition name="card-appear" appear>
        <div 
          class="drawer-card crop-card" 
          :class="{ 
             expanded: currentStep >= 0,
             active: currentStep === 0,
             collapsed: currentStep > 0 && selectedCrop
           }"
        >
          <div class="card-header" @click="toggleCard(0)">
            <div class="header-content">
              <span class="card-title">作物管理</span>
              <span v-if="selectedCrop && currentStep > 0" class="selected-info">
                已选择: {{ selectedCrop.cropname }}
              </span>
            </div>
            <div class="expand-arrow" :class="{ rotated: currentStep >= 0 }">
              <i class="el-icon-arrow-down"></i>
            </div>
          </div>
          
          <div class="card-content" v-show="currentStep >= 0">
            <!-- 搜索区域 -->
            <div class="search-area">
              <el-input
                v-model="cropSearchText"
                placeholder="搜索作物名称"
                prefix-icon="Search"
                clearable
                @input="handleCropSearch"
              />
            </div>
            
            <!-- 作物列表 -->
            <div class="crop-list">
              <div 
                v-for="crop in filteredCrops" 
                :key="crop.cropid"
                :class="['crop-item', { selected: selectedCrop?.cropid === crop.cropid }]"
                @click="selectCrop(crop)"
              >
                <div class="crop-info">
                  <div class="crop-name">{{ crop.cropname }}</div>
                  <div class="crop-desc">{{ crop.cropdescription }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </transition>

      <!-- 物候期管理卡片 -->
      <transition name="card-slide" appear>
        <div 
          v-if="selectedCrop"
          class="drawer-card period-card" 
          :class="{ 
            expanded: currentStep >= 1 && selectedCrop,
            active: currentStep === 1,
            collapsed: currentStep > 1 && selectedPeriod,
            disabled: !selectedCrop
          }"
        >
          <div class="card-header" @click="selectedCrop && toggleCard(1)">
            <div class="header-content">
              <span class="card-title">物候期管理</span>
              <span v-if="selectedPeriod && currentStep > 1" class="selected-info">
                已选择: {{ selectedPeriod.phenologicalperiodname }}
              </span>
            </div>
            <div class="expand-arrow" :class="{ rotated: currentStep >= 1 && selectedCrop }">
              <i class="el-icon-arrow-down"></i>
            </div>
          </div>
          
          <div class="card-content" v-show="currentStep >= 1 && selectedCrop">
            <div v-if="!selectedCrop" class="empty-state">
              <div class="empty-text">请先选择一个作物</div>
            </div>
            
            <div v-else>
              <div class="selected-crop-info">
                <span class="label">当前作物：</span>
                <span class="value">{{ selectedCrop.cropname }}</span>
              </div>
              
              <!-- 物候期列表 -->
              <div class="period-list">
                <div 
                  v-for="period in cropPeriods" 
                  :key="period.phenologicalperiodid"
                  :class="['period-item', { selected: selectedPeriod?.phenologicalperiodid === period.phenologicalperiodid }]"
                  @click="selectPeriod(period)"
                >
                  <div class="period-info">
                    <div class="period-name">{{ period.phenologicalperiodname }}</div>
                    <div class="period-time">
                      {{ formatDate(period.starttime) }} - {{ formatDate(period.endtime) }}
                    </div>
                    <div class="period-characteristics">{{ period.characteristics }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </transition>

      <!-- 指导信息管理卡片 -->
      <transition name="card-slide" appear>
        <div 
          v-if="selectedPeriod"
          class="drawer-card guidance-card" 
          :class="{ 
            expanded: currentStep >= 2 && selectedPeriod,
            active: currentStep === 2,
            disabled: !selectedPeriod
          }"
        >
          <div class="card-header" @click="selectedPeriod && toggleCard(2)">
            <div class="header-content">
              <span class="card-title">指导信息管理</span>
            </div>
            <div class="expand-arrow" :class="{ rotated: currentStep >= 2 && selectedPeriod }">
              <i class="el-icon-arrow-down"></i>
            </div>
          </div>
          
          <div class="card-content" v-show="currentStep >= 2 && selectedPeriod">
            <div v-if="!selectedPeriod" class="empty-state">
              <div class="empty-text">请先选择一个物候期</div>
            </div>
            
            <div v-else>
              <div class="selected-period-info">
                <span class="label">当前物候期：</span>
                <span class="value">{{ selectedPeriod.phenologicalperiodname }}</span>
              </div>
              
              <!-- 指导信息列表 -->
              <div class="guidance-list">
                <div 
                  v-for="guidance in periodGuidances" 
                  :key="guidance.guidanceid"
                  class="guidance-item"
                >
                  <div class="guidance-info">
                    <div class="guidance-header">
                      <div class="guidance-name">{{ guidance.guidancename }}</div>
                      <div class="guidance-type">{{ guidance.guidetype }}</div>
                    </div>
                    <div class="guidance-period">周期：{{ guidance.guidanceperiod }}</div>
                    <div class="guidance-implementation">{{ guidance.standardizedImplementation }}</div>
                    <div v-if="guidance.imageUrl" class="guidance-image">
                      <el-image 
                        :src="guidance.imageUrl" 
                        :preview-src-list="[guidance.imageUrl]"
                        fit="cover"
                        style="width: 60px; height: 60px; border-radius: 4px;"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { listCrops } from '@/api/agriculture/xctl/crops'
import { listPhenologicalperiods } from '@/api/agriculture/xctl/phenologicalperiods'
import { listPhenologicalguidance } from '@/api/agriculture/xctl/phenologicalguidance'

// 默认占位图
const defaultImage = '/images/default-guidance.png'

// 步骤定义
const steps = [
  { id: 'crop', title: '选择作物', description: '选择或管理作物信息' },
  { id: 'period', title: '物候期管理', description: '管理作物的生长周期' },
  { id: 'guidance', title: '指导信息', description: '管理生产指导信息' }
]

// 状态
const currentStep = ref(0)
const crops = ref([])
const periods = ref([])
const guidances = ref([])
const selectedCrop = ref(null)
const selectedPeriod = ref(null)
const cropSearchText = ref('')

// 过滤作物列表
const filteredCrops = computed(() => {
  if (!cropSearchText.value) return crops.value
  return crops.value.filter(crop =>
    crop.cropname.toLowerCase().includes(cropSearchText.value.toLowerCase())
  )
})

// 当前作物的物候期
const cropPeriods = computed(() => {
  if (!selectedCrop.value) return []
  return periods.value.filter(period => period.cropid === selectedCrop.value.cropid)
})

// 当前物候期的指导信息
const periodGuidances = computed(() => {
  if (!selectedPeriod.value) return []
  return guidances.value.filter(guidance => guidance.phenologicalperiodid === selectedPeriod.value.phenologicalperiodid)
})

// 方法
const setCurrentStep = (step) => currentStep.value = step
const toggleCard = (step) => currentStep.value = (currentStep.value === step ? step - 1 : step)

const selectCrop = (crop) => {
  selectedCrop.value = crop
  selectedPeriod.value = null
  currentStep.value = 1
  loadPeriods(crop.cropid)
}

const selectPeriod = (period) => {
  selectedPeriod.value = period
  currentStep.value = 2
  loadGuidances(period.phenologicalperiodid)
}

const handleCropSearch = () => {}

const formatDate = (dateString) => dateString ? new Date(dateString).toLocaleDateString('zh-CN') : ''

// 加载作物列表
const loadCrops = async () => {
  try {
    const response = await listCrops({})
    crops.value = response.rows || []
  } catch (error) {
    console.error('加载作物数据失败:', error)
  }
}

// 加载物候期列表
const loadPeriods = async (cropId) => {
  try {
    const response = await listPhenologicalperiods({ cropid: cropId })
    periods.value = response.rows || []
  } catch (error) {
    console.error('加载物候期数据失败:', error)
  }
}

// 加载指导信息列表（方案一：直连后端地址，不走 /dev-api）
const loadGuidances = async (periodId) => {
  try {
    const response = await listPhenologicalguidance({ phenologicalperiodid: periodId })
    guidances.value = (response.rows || []).map(item => {
      let url = item.imageUrl || ''
      if (url) {
        // 如果是 http/https 开头，直接使用
        if (!/^https?:\/\//i.test(url)) {
          // 去掉重复 /profile/ 前缀
          url = url.replace(/^\/+profile\/+/, '')
          // 直连后端，不走 dev-api
          url = `http://localhost:8080/profile/${url}`
        }
      } else {
        url = defaultImage
      }
      return { ...item, imageUrl: url }
    })
  } catch (error) {
    console.error('加载指导信息失败:', error)
  }
}

// 生命周期
onMounted(() => {
  loadCrops()
  currentStep.value = 0
})
</script>

<style scoped>
.phenology-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.page-subtitle {
  font-size: 16px;
  color: #7f8c8d;
  margin: 0;
}

.steps-indicator {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
  gap: 20px;
}

.step-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.step-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.step-item.active {
  border-color: #689f38;   /* 较深的绿色边框 */
  background: #c5e1a5;     /* 稍深的浅绿色背景 */
  color: #33691e;          /* 深绿色文字 */
}




.step-number {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #e9ecef;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 12px;
  font-size: 14px;
}

.step-item.active .step-number {
  background: rgba(104, 159, 56, 0.2);  /* 半透明绿色背景 */
  color: #33691e;                       /* 深绿色文字 */
}


.step-info {
  text-align: left;
}

.step-title {
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 4px;
}

.step-desc {
  font-size: 12px;
  opacity: 0.8;
}

.drawer-cards-container {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  flex-direction: row;
  gap: 20px;
  align-items: flex-start;
  min-height: 600px;
}

.drawer-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  border: 2px solid transparent;
  flex: 1;
  min-width: 300px;
  max-width: 450px;
  height: 580px;
}

.drawer-card.active {
  border-color: #689f38; /* 较深的绿色边框 */
  box-shadow: 0 8px 32px rgba(104, 159, 56, 0.2); /* 半透明绿色阴影 */
}



.drawer-card.collapsed {
  opacity: 0.7;
}

.drawer-card.disabled {
  opacity: 0.5;
  pointer-events: none;
}

.card-header {
  padding: 20px 24px;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  border-bottom: 1px solid #dee2e6;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: all 0.3s ease;
}

.card-header:hover {
  background: linear-gradient(135deg, #e9ecef, #dee2e6);
}

.drawer-card.active .card-header {
  background: linear-gradient(135deg, #c5e1a5, #aed581); /* 浅绿到稍深绿渐变 */
  color: #33691e; /* 深绿色文字 */
}


.header-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-icon {
  font-size: 24px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
}

.selected-info {
  font-size: 14px;
  opacity: 0.9;
  background: rgba(255, 255, 255, 0.2);
  padding: 4px 8px;
  border-radius: 6px;
}

.expand-arrow {
  transition: transform 0.3s ease;
  font-size: 16px;
}

.expand-arrow.rotated {
  transform: rotate(180deg);
}

.card-content {
  padding: 24px;
  animation: slideDown 0.3s ease;
  max-height: 480px;
  overflow-y: auto;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.search-area {
  margin-bottom: 20px;
}

.crop-list, .period-list, .guidance-list {
  display: grid;
  gap: 12px;
}

.crop-item, .period-item, .guidance-item {
  padding: 16px;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f8f9fa;
}

.crop-item:hover,
.period-item:hover {
  border-color: #689f38;       /* 较深绿边框 */
  background: #dcedc8;         /* 浅绿背景 */
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(104, 159, 56, 0.2); /* 绿色阴影 */
}



.crop-item.selected,
.period-item.selected {
  border-color: #689f38;       /* 较深绿边框 */
  background: #c5e1a5;         /* 浅绿色背景 */
  color: #33691e;              /* 深绿色文字 */
}



.crop-info, .period-info, .guidance-info {
  text-align: left;
}

.crop-name, .period-name, .guidance-name {
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 8px;
}

.crop-desc, .period-characteristics, .guidance-implementation {
  font-size: 14px;
  opacity: 0.8;
  line-height: 1.4;
}

.period-time {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.guidance-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.guidance-type {
  background: #c5e1a5;   /* 浅绿色背景 */
  color: #33691e;        /* 深绿色文字 */
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
}



.guidance-period {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.guidance-image {
  margin-top: 12px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
}

.selected-crop-info, .selected-period-info {
  background: #dcedc8;      /* 浅绿色背景 */
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  border-left: 4px solid #689f38;  /* 较深绿色左边框 */
}




.label {
  font-weight: 600;
  color: #666;
}

.value {
  color: #33691e; /* 深绿色文字 */
  font-weight: 600;
}

/* 动画效果 */
.card-appear-enter-active {
  animation: cardAppear 0.6s ease-out;
}

.card-slide-enter-active {
  animation: cardSlide 0.5s ease-out;
}

.card-slide-leave-active {
  animation: cardSlide 0.3s ease-in reverse;
}

@keyframes cardAppear {
  from {
    opacity: 0;
    transform: translateY(30px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

@keyframes cardSlide {
  from {
    opacity: 0;
    transform: translateX(50px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateX(0) scale(1);
  }
}

.card-content {
  transition: all 0.3s ease;
}

.card-content[v-show] {
  animation: contentExpand 0.3s ease;
}

@keyframes contentExpand {
  from {
    opacity: 0;
    max-height: 0;
  }
  to {
    opacity: 1;
    max-height: 1000px;
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .drawer-cards-container {
    max-width: 100%;
    padding: 0 20px;
  }
  
  .drawer-card {
    min-width: 280px;
    max-width: 400px;
  }
}

@media (max-width: 768px) {
  .steps-indicator {
    flex-direction: column;
    gap: 10px;
  }
  
  .step-item {
    padding: 12px 16px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .drawer-cards-container {
    flex-direction: column;
    min-height: auto;
  }
  
  .drawer-card {
    height: auto;
    min-height: 400px;
    max-width: 100%;
  }
  
  .card-header {
    padding: 16px 20px;
  }
  
  .card-content {
    padding: 20px;
    max-height: none;
  }
  
  .card-icon {
    font-size: 20px;
  }
  
  .card-title {
    font-size: 16px;
  }
}
</style>